<template>
  <el-header class="agreement-header">
    <HeaderDemo />
  </el-header>
  <!-- <el-container> -->
    
  <div class="agreement-wrapper">
    <el-affix :offset="10" style="height: 500px;">
      <div class="button-group">
        <el-button class="full-width-button" type="primary" @click="gotoAgreementDeal">默认合同</el-button>
        <el-button class="full-width-button gray-button">自定义合同</el-button>
      </div>
      <div class="agreement-left" :style="{ width: leftPanelWidth + 'px' }">
        双方信息：
        <SideBarLibrary @componentDropped="handleComponentDropped" />
        剧本基本信息：
        <SideBarWork @componentDropped="handleComponentDropped2"  />
        授权内容：
        <SideBarShouquanneirong @componentDropped="handleComponentDropped3"
         />
          授权期限：
        <SideBarShouquanqixian @componentDropped="handleComponentDropped4"
        />
          费用与支付方式：
        <SideBarFeiYongZhiFu @componentDropped="handleComponentDropped5" />
        权利与义务：
        <SideBarQuanliYiWu @componentDropped="handleComponentDropped6"  />
        违约责任：
        <SideBarWeiYue @componentDropped="handleComponentDropped7" />
      </div>
    </el-affix>


    <!-- 拖动分隔符 -->
    <div class="resizer" @mousedown="initResize" />

    <div class="agreement-container">
      <h1>短视频剧本授权协议</h1>
      <div class="agreement-content">



        <div class="document-editor" @dragover.prevent @drop="drop($event)">
          <draggable v-model="documentLayout" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onDragStart($event, element)">
                <!-- <component :is="componentMapping[element]" /> -->
                <!-- <button @click="handleComponentDropped">移除</button> 新增这个按钮用于移除 -->
                <!-- 在这里使用 UserView1 组件，并将 work 数据传递给子组件 -->
                <component :is="componentMapping[element]" :work="work" :writer="writer" :user="user" />
              </div>
            </template>
          </draggable>
        </div>



        <p>
          鉴于甲方为短视频剧本《<span class="editable" contenteditable="true">{{ work.wname }}</span>》（以下简称“剧本”）的唯一合法著作权人，
          根据《中华人民共和国著作权法》及相关法律法规的规定，甲乙双方经友好协商，就甲方授权乙方使用该剧本达成如下协议：
        </p>

        <h2>第一条 剧本基本信息</h2>

        <div class="document-editor" @dragover.prevent @drop="drop2($event)">
          <draggable v-model="documentLayout2" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onDragStart($event, element)">

                <component :is="componentMapping[element]" :work="work" :writer="writer" :user="user" />
              </div>
            </template>
          </draggable>
        </div>


        <h2>第二条 授权内容</h2>
        <!-- <p>shichang:{{ authorization.time }}+{{ authorization.platform }}</p> -->

        <div class="document-editor" @dragover.prevent @drop="drop3($event)">
          <draggable v-model="documentLayout3" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onMouseDown($event, element)" @mouseup="onMouseUp" 
              @mouseleave="onMouseLeave">

                <component :is="componentMapping[element]" :work="work" :hetong="hetong" :user="user" />
              </div>
            </template>
          </draggable>
        </div>

        <h2>第三条 授权期限</h2>
        <!-- 期限：{{ authorization.age_limit }} -->
        <!-- <p>
          本协议自双方签字盖章之日起生效，授权期限为<span class="editable" contenteditable="true" @input="updateage_limit">{{ work.age_limit
            }}</span>年。授权期限届满后，乙方应立即停止使用剧本，并删除或销毁所有基于本协议制作的改编作品。
        </p> -->
        <div class="document-editor" @dragover.prevent @drop="drop4($event)">
          <draggable v-model="documentLayout4" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onDragStart($event, element)">

                <component :is="componentMapping[element]" :work="work" :hetong="hetong" :user="user" />
              </div>
            </template>
          </draggable>
        </div>

        <h2>第四条 费用与支付方式</h2>
          <!-- 支付feiyong :{{ authorization.authorization_fee }} -->
        <div class="document-editor" @dragover.prevent @drop="drop5($event)">
          <draggable v-model="documentLayout5" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onDragStart($event, element)">

                <component :is="componentMapping[element]" :work="work" :hetong="hetong" :user="user" />
              </div>
            </template>
          </draggable>
        </div>


        <h2>第五条 权利与义务</h2>
        <div class="document-editor" @dragover.prevent @drop="drop6($event)">
          <draggable v-model="documentLayout6" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onDragStart($event, element)">

                <component :is="componentMapping[element]" :work="work" :hetong="hetong" :user="user" />
              </div>
            </template>
          </draggable>
        </div>
        <h2>第六条 违约责任</h2>
        <!-- <p>任何一方违反本协议约定，应承担违约责任，赔偿守约方因此遭受的直接经济损失。</p> -->
        <div class="document-editor" @dragover.prevent @drop="drop7($event)">
          <draggable v-model="documentLayout7" :animation="200">
            <template #item="{ element }">
              <div class="dropped-component" draggable="true" @mousedown="onDragStart($event, element)">

                <component :is="componentMapping[element]" :work="work" :hetong="hetong" :user="user" />
              </div>
            </template>
          </draggable>
        </div>
        <h2>第七条 争议解决</h2>
        <p>因本协议引起的或与本协议有关的任何争议，双方应首先通过友好协商解决；协商不成的，任何一方均有权将争议提交甲方所在地有管辖权的人民法院诉讼解决。</p>

        <h2>第八条 其他条款</h2>
        <p>8.1 本协议未尽事宜，双方可另行签订补充协议，补充协议与本协议具有同等法律效力。</p>
        <p>8.2 本协议一式两份，甲乙双方各执一份，自双方签字或盖章之日起生效。</p>

        <div class="sign-section">
          <div class="sign-block">
            <p>
              甲方（签字）：
              <span v-if="signatures.partyA" class="signature-image">
                <img :src="signatures.partyA" alt="甲方签字" />
              </span>
              <span v-else class="editable"></span>
            </p>
            <p>
              日期：
              <span class="date-display">{{ datePartyA }}</span>
            </p>
          </div>
          <div class="sign-block">
            <p>
              乙方（签字）：
              <span v-if="signatures.partyB" class="signature-image">
                <img :src="signatures.partyB" alt="乙方签字" />
              </span>
              <span v-else class="editable"></span>
            </p>
            <p>
              日期：
              <span class="date-display">{{ datePartyB }}</span>
            </p>
          </div>
        </div>
      </div>

      <!-- 签名弹出框 -->
      <div v-if="showSignaturePad" class="signature-pad-modal">
        <canvas ref="signaturePad" class="signature-canvas"></canvas>
        <button @click="saveSignature">保存签名</button>
        <button @click="clearSignature">清除签名</button>
        <button @click="closeSignaturePad">关闭</button>
      </div>

      <div class="action-buttons">
        <button @click="submitAgreement">保存设置</button>
      </div>
    </div>

  </div>
  <!-- </el-container> -->
<!-- <FooterComp/> -->
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, inject, onBeforeUnmount,computed  } from 'vue';
import SignaturePad from 'signature_pad';
import { useRouter, useRoute } from 'vue-router'
import FooterComp from '../components/FooterComp.vue';
import { ElMessage } from 'element-plus';
import CryptoJS from 'crypto-js';
import HeaderDemo from '../components/HeaderDemo.vue';
import SideBarWork from '../Sidebar/SideBarWork.vue';
import SideBarLibrary from '../Sidebar/SideBarLibrary.vue';
import SideBarShouquanneirong from '../Sidebar/SideBarShouquanneirong.vue';
import SideBarShouquanqixian from '../Sidebar/SideBarShouquanQiXIan.vue';
import SideBarFeiYongZhiFu from '../Sidebar/SideBarFeiYongZhiFu.vue';
import SideBarQuanliYiWu from '../Sidebar/SideBarQuanliYiWu.vue';
import SideBarWeiYue from '../Sidebar/SideBarWeiYue.vue';
import draggable from 'vuedraggable';
import workdata1 from '../Sidebar/sidebar/workdata1.vue';
import UserView1 from '../Sidebar/sidebar/UserView1.vue';
import ShouQuanNeirong1 from '../Sidebar/sidebar/ShouQuanNeirong1.vue';
import Shouquanqixian1 from '../Sidebar/sidebar/Shouquanqixian1.vue';
import FeiYongZhiFu1 from '../Sidebar/sidebar/FeiYongZhiFu1.vue';
import QuanLiYiWu1 from '../Sidebar/sidebar/QuanLiYiWu1.vue';
import WeiYue1 from '../Sidebar/sidebar/WeiYue1.vue';
// import ShouQuqanNeirong from '../util/ShouquanNeirong'
// import store from '../util/store';
// import EventBus from '../util/EventBus';
import { useStore } from 'vuex';
import { ca } from 'element-plus/lib/locale/index.js';
// import { draggable } from 'element-plus/es/components/color-picker/src/utils/draggable.mjs';
const axios = inject('axios') //注入 axios
const router = useRouter(); // 获取 router 实例
// 获取路由信息
const route = useRoute();
const store = useStore();
const userId = 'user123';
// 从 Vuex 中获取授权内容
const authorization = computed(() => store.getters.getAuthorization);

//允许拖入的数组
const allowedComponentTypes = ['UserView1'];
const allowedComponentTypes2 = ['workdata1',];
const allowedComponentTypes3 = ['ShouQuanNeirong1',];
const allowedComponentTypes4 = ['Shouquanqixian1',];
const allowedComponentTypes5 = ['FeiYongZhiFu1',];
const allowedComponentTypes6 = ['QuanLiYiWu1',];
const allowedComponentTypes7 = ['WeiYue1',];
//数组1
const documentLayout = ref([]);
const documentLayout2 = ref([]);
const documentLayout3 = ref([]);
const documentLayout4 = ref([]);
const documentLayout5 = ref([]);
const documentLayout6 = ref([]);
const documentLayout7 = ref([]);

const history = ref([]); // 用于存储历史记录
let draggedElement = null; // 记录当前拖动的组件
let pressTimer = null; // 定时器
const longPressTime = 500; // 长按的时间


//组件映射
const componentMapping = {
  'UserView1': UserView1,
  'workdata1': workdata1,
  'ShouQuanNeirong1': ShouQuanNeirong1,
  'Shouquanqixian1': Shouquanqixian1,
  'FeiYongZhiFu1': FeiYongZhiFu1,
  'QuanLiYiWu1': QuanLiYiWu1,
  'WeiYue1': WeiYue1,

};

//解密token
function getToken() {
  const encryptedToken = localStorage.getItem('token');
  if (encryptedToken) {
    const secretKey = 'your_secret_key'; // 使用相同的密钥
    const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
    const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
    return decryptedToken;
  }
  return null;
}

const onMouseDown = (event, element) => {
  pressTimer = setTimeout(() => {
    event.preventDefault();
    event.dataTransfer.setData("text/plain", element); // 设置拖动数据
    event.dataTransfer.effectAllowed = "move"; // 拖动效果设置
  }, longPressTime);
};

const onMouseUp = () => {
  clearTimeout(pressTimer); // 清理定时器
};

const onMouseLeave = () => {
  clearTimeout(pressTimer); // 清理定时器
};

// 处理拖动开始事件
const onDragStart = (event, element) => {
  event.dataTransfer.setData("text/plain", element); // 将组件类型或标识符存储到拖动数据中
  draggedElement = element; // 记录当前拖动的组件
};
// 处理 drop 事件
const drop = (event) => {
  //event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};

const drop2 = (event) => {
  event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes2.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout2.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};
const drop3 = (event) => {
  event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes3.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout3.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};
const drop4 = (event) => {
  event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes4.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout4.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};
const drop5 = (event) => {
  event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes5.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout5.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};
const drop6 = (event) => {
  event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes6.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout6.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};
const drop7 = (event) => {
  event.preventDefault(); // 防止默认行为 (比如打开链接)
  const componentType = event.dataTransfer.getData("text/plain");
  console.log(`拖动开始：${componentType}`);
  // if (componentMapping[componentType]) { // 验证组件类型有效性
  if (componentMapping[componentType]) { // 验证组件类型有效性
    if (allowedComponentTypes7.includes(componentType)) {
      // saveCurrentState(); // 保存当前状态
      documentLayout7.value.push(componentType); // 向文档布局添加组件
    } else {
      console.log('此处不允许添加的组件类型:', componentType);
    }
  } else {
    console.log('无效的组件类型:', componentType);
  }
};
// 处理组件拖回
// const dropInLibrary = (event) => {
//   const componentType = event.dataTransfer.getData("text/plain");
//   console.log(`拖回的组件: ${componentType}`); // 在这里可以添加逻辑
// };
//拖回组件
const handleComponentDropped = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  //documentLayout.value.push(componentType); // 将组件类型添加到布局数组中
  // 你可以输出 documentLayout 来查看当前状态
  // saveCurrentState();
  documentLayout.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};
const handleComponentDropped2 = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  //documentLayout2.value.push(componentType); // 将组件类型添加到布局数组中
  // 你可以输出 documentLayout 来查看当前状态
  // saveCurrentState();
  documentLayout2.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};
const handleComponentDropped3 = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  // saveCurrentState();
  documentLayout3.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};
const handleComponentDropped4 = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  // saveCurrentState();
  documentLayout4.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};
const handleComponentDropped5 = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  // saveCurrentState();
  documentLayout5.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};
const handleComponentDropped6 = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  // saveCurrentState();
  documentLayout6.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};
const handleComponentDropped7 = (componentType) => {
  console.log(`添加组件到 documentLayout: ${componentType}`);
  // saveCurrentState();
  documentLayout7.value.splice(componentType, 1); // 移除组件在布局中的记录
  console.log('当前文档布局:', documentLayout.value);
};

// 撤回功能
// const undo = () => {
//   if (history.value.length > 0) {
//     console.log('撤回操作');

//     documentLayout.value = history.value.pop(); // 恢复上一个状态
//   }
// };

// 保存当前状态到历史记录
// const saveCurrentState = () => {
//   history.value.push([...documentLayout.value]); // 深拷贝当前状态并添加到历史记录
// };

console.log("id:" + route.params.id)


// State Variables
const chineseAmount = ref('_________'); // 初始大写内容
const showSignaturePad = ref(false); // 控制签名框显示
const currentSignatureParty = ref<string | null>(null); // 当前签名的用户（甲方或乙方）
const signatures = ref<{ partyA: string | null; partyB: string | null }>({ partyA: null, partyB: null }); // 存储签名图片
const signaturePad = ref<SignaturePad | null>(null); // 存储 SignaturePad 实例
const canvasRef = ref<HTMLCanvasElement | null>(null); // canvas 表单元素

// 业务逻辑
const openSignaturePad = (party: 'partyA' | 'partyB') => {
  console.log('openSignaturePad');
  currentSignatureParty.value = party;
  showSignaturePad.value = true;
  nextTick(() => {
    initSignaturePad();
  });
};

const initSignaturePad = () => {
  if (canvasRef.value) {
    const canvas = canvasRef.value;
    // 设置 canvas 宽度和高度为实际显示尺寸
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
    signaturePad.value = new SignaturePad(canvas);
  }
};

const saveSignature = () => {
  if (signaturePad.value?.isEmpty()) {
    alert("请签名！");
  } else {
    const dataUrl = signaturePad.value?.toDataURL();
    if (dataUrl) {
      signatures.value[currentSignatureParty.value as 'partyA' | 'partyB'] = dataUrl;
      // 发送签名到后端
      uploadSignature(dataUrl, currentSignatureParty.value);
      closeSignaturePad();
    }
  }
};

const uploadSignature = (dataUrl: string, party: string | null) => {
  const signatureData = {
    party, // 签名的用户（甲方/乙方）
    signature: dataUrl, // 签名的 base64 数据
  };

  fetch("http://localhost:3000/upload-signature", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(signatureData),
  })
    .then(response => response.json())
    .then(data => {
      console.log("Signature saved:", data);
    })
    .catch(error => {
      console.error("Error saving signature:", error);
    });
};

const clearSignature = () => {
  signaturePad.value?.clear();
};

const closeSignaturePad = () => {
  showSignaturePad.value = false;
};

const convertToChinese = (event: InputEvent) => {
  const value = (event.target as HTMLElement).innerText.trim();
  console.log("=========" + value);
  work.value.authorization_fee = value;
  if (value && !isNaN(Number(value))) {
    chineseAmount.value = numberToChinese(Number(value));
    work.Authorization_fee = value;
    console.log("输入的金额：" + value)
  } else {
    chineseAmount.value = '_________'; // 当内容为空或无效时显示默认下划线
  }
  convertToChinese2(value)
};

const convertToChinese2 = (value) => {
  console.log("convertToChinese2");

  // 如果输入值是空则直接赋值为下划线 
  console.log("value.trim():" + value.trim());

  if (value.trim() === '') {
    chineseAmount.value = '_________'; // 当内容为空时显示下划线
    work.value.authorization_fee = ''; // 清空费用
    console.log("work.value.authorization_fee:" + work.value.authorization_fee);

    return; // 退出函数
  }
  // 执行有效性检查，确保是可转换的数字（包括支持负数和小数）
  const numericValue = Number(value);
  console.log("numericValue:" + numericValue);
  if (!isNaN(numericValue) && isFinite(numericValue)) {
    console.log("isFinite(numericValue):" + isFinite(numericValue));
    console.log("numericValue:" + numericValue);
    console.log("value:" + value);
    chineseAmount.value = numberToChinese(numericValue);
    console.log("chineseAmount.value:" + chineseAmount.value);

    work.authorization_fee = value;
    console.log("输入的金额：" + value)
  } else {
    chineseAmount.value = '_________'; // 当内容为空或无效时显示默认下划线
    work.authorization_fee = ''; // 清空费用
  }
}

// 数字转大写的函数
function numberToChinese(n: string): string {
  // 校验输入是否为数字
  if (!/^\d*(\.\d*)?$/.test(n)) return "输入的不是数字";

  const units = ["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"];
  const chars = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];

  let num = String(n);
  let resultWithUnit = "";
  let decimalPart = "";

  // 处理小数部分
  if (num.indexOf(".") !== -1) {
    const decimals = num.split(".")[1];
    decimalPart = "点";
    for (let i = 0; i < decimals.length; i++) {
      decimalPart += chars[Number(decimals[i])];
    }
    num = num.split(".")[0]; // 去掉小数部分
  }

  let unitPosition = 0; // 用于跟踪当前位对应的单位
  let zeroFlag = false; // 用于跟踪零的连续出现
  let hasNonZero = false; // 标记是否出现过非零数字

  // 处理整数部分
  for (let i = num.length - 1; i >= 0; i--) {
    const currentNum = num[i];
    const unitIndex = unitPosition % 12; // 使用12个单位

    if (currentNum === "0") {
      zeroFlag = true;
    } else {
      if (zeroFlag && hasNonZero) {
        resultWithUnit = chars[0] + resultWithUnit;
        zeroFlag = false; // 连续零结束
      }
      resultWithUnit = chars[Number(currentNum)] + units[unitIndex] + resultWithUnit;
      hasNonZero = true; // 标记为已出现非零数字
    }

    // 添加单位 "万" 或 "亿"
    if (unitIndex === 4 && i > 0) {
      resultWithUnit = "万" + resultWithUnit;
    }
    if (unitIndex === 8 && i > 0) {
      resultWithUnit = "亿" + resultWithUnit;
    }

    unitPosition++;
  }

  // 特殊处理：“壹拾”应改为“拾”
  if (resultWithUnit.startsWith("壹拾")) {
    resultWithUnit = resultWithUnit.replace("壹拾", "拾");
  }

  // 去掉“亿万”的情况，比如输入1000000000
  resultWithUnit = resultWithUnit.replace(/亿万/g, "亿");

  // 去掉末尾的“零”
  resultWithUnit = resultWithUnit.replace(/零+$/, "");

  return resultWithUnit + decimalPart;
}



// 剧本
const work = ref({
  wname: '', //剧本名称
  typeID: '',  //类型
  copyright: '', //版权登记号
  record: '',  //备案号
  time: '', //授权时长
  platform: '',  //授权平台
  age_limit: '', //授权年限
  authorization_fee: '',  //授权费用

}); // 示例数据

// 获取剧本信息
const fetchBookInfo = async (id) => {
  console.log("合同=》获取到的剧本id：" + id);

  const WID = id;
  console.log("合同=》获取到的剧本id：" + JSON.stringify(WID, null, 2));
  try {
    const response = await axios.get(`http://localhost:8080/api/getwork/${WID}`); // 替换为实际的API端点
    work.value = response.data; // 假设后端返回的对象结构与book对象一致


    console.log("获取剧本信息成功：" + JSON.stringify(work.value, null, 2));
    convertToChinese2(work.value.authorization_fee)

    // 获取剧本类型
    await fetchWorkType(work.value.typeID); // 确保此时 work.value.TYPEID 已经是最新

  } catch (error) {
    console.error('Error fetching book info:', error);
  }
};

// //获取剧本题材列表
const scriptTypes = ref([]);  // 用于存储从后端获取的题材
const fetchScriptTypes = async (wid) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/getworklabelByWid/${wid}`);
    scriptTypes.value = response.data.data; // 更新题材数据
    console.log('获取题材列表成功：', JSON.stringify(scriptTypes.value, null, 2));
    // console.log('获取题材列表成功：', JSON.stringify(scriptTypes[0].value.bname, null, 2));
  } catch (error) {
    console.error('Error fetching script types:', error);
  }
};

//获取剧本类
const work_type = ref('');
const fetchWorkType = async (id) => {

  try {
    const response = await axios.get(`http://localhost:8080/api/getworktypeByThemeId/${id}`);
    work_type.value = response.data; // 更新题材数据
    console.log('获取剧本类型成功：', JSON.stringify(work_type.value, null, 2));
    // console.log('获取题材列表成功：', JSON.stringify(work_type[0].value.bname, null))
  } catch (error) {
    console.error('遇到错误', error);
  }
}

//获取编剧信息
const writer = ref({
  account: '',
  uname: '',
  real_name: '',
});
//用户信息，版权购买方
const user = ref({
  account: '',
  uname: '',
  real_name: '',
});

// 获取登录用户信息
const fetchWriterInfo = async () => {
  console.log("获取用户信息");
  const token = getToken();
  try {
    const response = await axios.get('http://localhost:8080/user/getuser', {
      headers: {
        Authorization: 'Bearer ' + token,
      }
    });
    user.value = response.data.user; // 更新编剧数据
    user.account = user.value.uid;

    console.log('获取编剧信息成功：', user.value);
    console.log("user.account" + user.account);

  } catch (error) {
    console.error('Error fetching writer info:', error);
  }
};

//合同初始化数据
const hetong = ref({
  // 合同信息
  wid: '',   // 剧本id
  ownerId: '',   // 剧本作者id
  licensee_id: '',   // 剧本购买方id
  transaction_amount: '',    // 合同金额
  time: '',    // 授权时长
  platform: '',  // 授权平台
  age_limit: '', // 授权年限
  partyA: '',    // 甲方签名（授权方）
  timeA: '', // 甲方签名时间
  partyB: '',    // 乙方签名（被授权方）
  timeB: '', // 乙方签名时间
  flow: '', // 合同状态
})
//获取合同的初始化数据
const fetchContractInfo = async (wid) => {
  //获取用户token
  const Token = getToken();
  work.value.wid = wid;
  try {
    const response = await axios.post(`http://localhost:8080/api/getTransaction`, work.value, {
      headers: {
        'Authorization': 'Bearer ' + Token,
        'Content-Type': 'application/json',
      },
    });
    hetong.value = response.data.data; // 假设后端返回的对象结构与work一致
    console.log("获取合同信息成功：", JSON.stringify(hetong.value, null, 2));
    //判断流程
    switch (hetong.value.flow) {
      case "1":
        FlowText.value = "交流中";
        break;
      case "2":
        FlowText.value = "版权方确认中";
        break;
      case "3":
        FlowText.value = "平台确认中";
        break;
      case "4":
        FlowText.value = "流程关闭";
        break;
    }
    convertToChinese2(hetong.value.transaction_amount)
  } catch (error) {
    console.error('出现错误：', error);
  }
}

//获取版权所有者信息（通过剧本uid）
const fetchWriterInfoByUid = async (uid: string) => {
  const Token = getToken();
  console.log("获取版权所有者信息:" + uid);
  try {
    const response = await axios.post(`http://localhost:8080/user/getUserById/${uid}`, null, {
      headers: {
        Authorization: 'Bearer ' + Token,
      }
    });
    console.log('获取编剧信息成功：', response.data.data);
    writer.value = response.data.data; // 更新编剧数据
    console.log('获取编剧信息成功：', writer.value);
    touxiangUrl.value = 'http://localhost:8080/api/images/' + writer.value.headlmg;
  } catch (error) { }
}

//// 用于存储从子组件接收到的输入数据
//授权内容子组件
const NeiRong = ref({time:'',platform:''});

//获取用户输入
// const handleInput = (data) => {
//   hetong.value.time.value = data;
//   console.log('Received data from child:', data);
  
//   console.log('Updated:', hetong.value.time.value);
// }
// const handleUpdateValue = (value) => {
//   inputtedValue.value = value; // 更新输入的值

//   console.log('获取到的输入值:', inputtedValue.value);
// };


const updateTime = (event) => {
  work.value.Time = event.target.innerText; // 更新 Time 字段
};
const updateplatform = (event) => {
  work.value.platform = event.target.innerText; // 更新 Time 字段
};
const updateage_limit = (event) => {
  work.value.age_limit = event.target.innerText; // 更新 Time 字段
};
// 提交修改
function submitAgreement() {
  console.log("修改信息："+JSON.stringify(authorization.value, null, 2));
  console.log("组件信息documentLayout："+documentLayout.value);
  console.log("组件信息documentLayout2："+documentLayout2.value);
  console.log("组件信息documentLayout3："+documentLayout3.value);
  console.log("组件信息documentLayout4："+documentLayout4.value);
  console.log("组件信息documentLayout5："+documentLayout5.value);
  console.log("组件信息documentLayout6："+documentLayout6.value);
  console.log("组件信息documentLayout7："+documentLayout7.value);
  // console.log("组件信息documentLayout8："+documentLayout8);
  
  console.log('提交修改');
  const uWork = {
    wid: route.params.id,
    time: work.value.Time,
    age_limit: work.value.age_limit,
    authorization_fee: work.value.authorization_fee,
    platform: work.value.platform,
  };

  const HetongZujian = {
    wid:route.query.wid as string,
    layout_data1:documentLayout.value,
    layout_data2:documentLayout2.value,
    layout_data3:documentLayout3.value,
    layout_data4:documentLayout4.value,
    layout_data5:documentLayout5.value,
    layout_data6:documentLayout6.value,
    layout_data7:documentLayout7.value,
    // layout_data8:documentLayout8,
    // layout_data9:documentLayout9,
    // layout_data10:documentLayout10,
  }

  //解密token
  const token = getToken();
  console.log("保存的组件数据为：:"+HetongZujian);

  //判断HetongZujian中的信息任意一下为空都无法进行保存
  if (
    documentLayout.value == '' ||
    documentLayout2.value == '' ||
    documentLayout3.value == '' ||
    documentLayout4.value == '' ||
    documentLayout5.value == '' ||
    documentLayout6.value == '' ||
    documentLayout7.value == ''
    // ||
    // documentLayout8 == ''

  ) {
    ElMessage.error('请填写完整信息');
    return;
  }
  
  //保存组件信息
  try {
    axios.post('http://localhost:8080/api/addworkzujian', HetongZujian, {
        headers: {
            'Authorization': 'Bearer ' +token // 添加 Authorization 头
        }
    })
    .then(function (response) {
        console.log(response);
        console.log("response.data.data.code: " + response.data.data.code);

        if (response.data.data.code == '200') {
          ElMessage({
            message: '保存成功',
            type: 'success',
          });
            console.log('保存成功');
            // 在此处添加成功后的逻辑
        } else {
            console.log('保存失败，错误代码: ' + response.data.data.code);
            ElMessage({
                message: '保存失败，错误代码: ' + response.data.data.code,
                type: 'error',
            });
            // 在此处处理其他错误情况
        }
    })
    .catch(function (error) {
        console.error('请求错误:', error);
        ElMessage({
            message: '保存失败，请检查网络连接',
            type: 'error',
        });
    });
} catch (error) {
    console.error('保存组件信息时发生错误:', error);
    ElMessage({
        message: '保存失败，请检查网络连接',
        type: 'error',
    });
}



  // try {
  //   // console.log("我认可："+JSON.stringify(uWork.value, null, 2))
  //   console.log("Submitting work:", uWork);
  //   axios({
  //     method: 'post',
  //     url: 'http://localhost:8080/api/updateworkByContract',
  //     data: uWork,
  //   })
  //     .then(function (response) {
  //       console.log(response)
  //       console.log("response.data.data.code" + response.data.data.code);

  //       if (response.data.data.code == '200') {
  //         ElMessage({
  //           message: '修改成功',
  //           type: 'success',
  //           plain: true
  //         })
  //       }
  //     })




  // } catch (error) {
  //   console.error("提交修改失败：" + error);
  // }

};

//获取合同组件信息
const fetchWorkZujian = async (wid) => {
  const Token = getToken();
  console.log("获取合同组件信息");
  console.log("wid"+wid);
  const HetongZujian = {
    wid:route.query.wid as string,
  }
  
  try {
    const response = await axios.post(`http://localhost:8080/api/getHetongZujian/`,HetongZujian, {
      headers: {
        Authorization: 'Bearer ' + Token,
      }
    });
    console.log('获取合同组件信息成功：', response.data.data);
    documentLayout.value = response.data.data.layout_data1;
    documentLayout2.value = response.data.data.layout_data2;
    documentLayout3.value = response.data.data.layout_data3;
    documentLayout4.value = response.data.data.layout_data4;
    documentLayout5.value = response.data.data.layout_data5;
    documentLayout6.value = response.data.data.layout_data6;
    documentLayout7.value = response.data.data.layout_data7;
    documentLayout2
  }catch (error) {
    console.error("获取合同组件信息失败：" + error);
  }
}



//组件栏滑动设置宽度
const leftPanelWidth = ref(250); // 初始化左侧面板宽度
// 用于存储拖动的初始位置和宽度
let startX = 0;
let startWidth = 0;
let isResizing = false;

const initResize = (e) => {

  // 记录初始位置
  startX = e.clientX;
  startWidth = leftPanelWidth.value;
  isResizing = true;
  // 添加事件监听，使用 requestAnimationFrame 来优化性能
  document.addEventListener("mousemove", resizePanel);
  document.addEventListener("mouseup", stopResize);
};
const resizePanel = (e) => {
  if (isResizing) {
    // 使用 requestAnimationFrame 来避免卡顿
    requestAnimationFrame(() => {
      const newWidth = Math.max(100, startWidth + (e.clientX - startX)); // 确保最小宽度
      leftPanelWidth.value = Math.min(newWidth, 550); // 设置最大宽度
    });
  }
};
const stopResize = () => {
  isResizing = false; // 重置状态
  document.removeEventListener("mousemove", resizePanel);
  document.removeEventListener("mouseup", stopResize);
};
// 禁用其他区域的滚动
const handleWheel = (event) => {
  isResizing = false;
  document.removeEventListener("mousemove", resizePanel);
  document.removeEventListener("mouseup", stopResize);
};


//跳转到默认合同页面
const gotoAgreementDeal = () => {
  router.push('/agreementdeal'); // 路由跳转到 /agreementdeal 页面
};

// 页面挂载后获取书籍信息
onMounted(async () => {
  

  // 获取路径下的 id
  const wid = route.query.wid as string;
  console.log('路由参数:', wid);
  await fetchBookInfo(wid); //获取剧本信息
  await fetchScriptTypes(wid); // 获取题材列表
  await fetchWorkType(work.value.typeID);//获取剧本类型，使用更新后的 `typeID`
  await fetchWriterInfo();  //获取编剧信息
  await fetchWriterInfoByUid(work.value.uid)
  await fetchContractInfo(wid);// 获取合同信息
  await fetchWorkZujian(wid);
  //checkUserIdentity();  // 检查用户身份
//EventBus.$on('update-input', handleUpdateValue); // 订阅事件

  //document.addEventListener("wheel", handleWheel, { passive: false }); // 禁止页面滚动

});

// 在 beforeUnmount 中移除事件监听
// onBeforeUnmount(() => {
//   document.removeEventListener("wheel", handleWheel);
//   EventBus.$on('update-input', handleUpdateValue); // 订阅事件
// });
</script>

<style scoped>
.agreement-header {
  height: 90px;
  background-color: #131414;
  /* 更加醒目的蓝色 */
  color: white;
  /* 文字颜色 */
  padding: 10px 20px;
  /* 内边距 */
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
  /* 添加阴影效果 */
  margin-bottom: 50px;
}

.agreement-wrapper {
  display: flex;
  /* 使用 Flexbox 布局 */
  /* justify-content: flex-start; */
  /* 更改为 flex-start */
  /* 在主轴方向上分散对齐 */
}

.button-group {
  display: flex; /* 使用 Flexbox 布局 */
  width: 100%; /* 容器宽度 */
}

.full-width-button {
  flex: 1; /* 使按钮填满父元素，均匀分配宽度 */
  border-radius: 0; /* 去掉圆角 */
  margin: 0; /* 清除默认的边距 */
}

.gray-button {
  background-color: #ccc; /* 设置灰色背景 */
  border: none; /* 去掉边框 */
  color: #fff; /* 设置文字为白色 */
  cursor: default; /* 禁用手型光标 */
}

/* 去掉点击效果 */
.gray-button:focus,
.gray-button:hover {
  background-color: #ccc; /* 保持灰色不变 */
}

.agreement-left {
  /* min-height: 100vh; */
  /* 确保左侧部分高度为满屏高度 */
  height: 880px;
  /* Safari */
  position: sticky;
  top: 0;
  /* Fixed top offset */
  border-right: 1px solid #ddd;
  /*overflow-y: auto;  允许垂直滚动 */
  overflow: auto;
  /* 允许滚动 */
  /* 分隔线 */
  padding: 10px;
  /* 内边距 */
  background-color: #f5f5f5;
  /* 背景色，便于视觉分隔 */
  /* overflow: hidden; */
  /* 确保内容不会影响布局 */
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  /*添加右侧阴影效果*/
  overflow-y: scroll; /* 允许垂直滚动 */
  scrollbar-width: thin; /* Firefox 不显示滚动条 */
  scrollbar-color: transparent transparent; /* Firefox 颜色设置 */
}

/* 拖动分隔符的样式 */
.resizer {
  cursor: ew-resize;
  width: 10px;
  /* 分隔符的宽度 */
  background-color: transparent;
  /* 背景色 */
  z-index: 1;
  /* 确保位于较高的 z-index */
}

/* 主容器样式 */
.agreement-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 30px;
  font-family: 'Arial', sans-serif;
  line-height: 1.6;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}


/* 标题样式 */
h1 {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  /* 主文字颜色 */
  margin-bottom: 20px;
  /* 增加与其它元素的间距 */
}

/* 段落内容样式 */
p {
  text-align: justify;
  text-indent: 2em;
  /* 首行缩进 */
}

/* 二级标题样式 */
h2 {
  font-size: 18px;
  margin-top: 20px;
  font-weight: bold;
}

/* 可编辑区域样式 */
.editable {
  position: relative;
  outline: none;
  display: inline-block;
  min-width: 120px;
  cursor: not-allowed;
  /* 禁用状态的鼠标样式 */
}



.editable:before {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-bottom: 1px solid black;
}

.date-display {
  cursor: default;
  /* 指针样式 */
}

/* 签名区域样式 */
.sign-section {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
}

.sign-block {
  text-align: left;
  width: 45%;
  cursor: not-allowed;
  /* 禁用状态的鼠标样式 */
}

.sign-block p {
  margin-bottom: 10px;
}

/* 按钮样式 */
button {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

/* 签名图片 */
.signature-image img {
  max-height: 50px;
  border-bottom: 1px solid black;
  cursor: default;
  cursor: not-allowed;
  /* 禁用状态的鼠标样式 */
}

/* 签名区域样式 */
.editable {
  cursor: pointer;
}

/* 签名弹出框样式 */
.signature-pad-modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.signature-canvas {
  border: 1px solid black;
  width: 100%;
  height: 200px;
  display: block;
}

.disabled-area {
  cursor: not-allowed;
  /* 禁用状态的鼠标样式 */
}

.document-editor {
  background-color: #ffffff;
  min-height: 50px;
  width: 100%;
  z-index: 10;
  /* 设置较高的z-index */
}
</style>